//
//  HMComposeViewController.swift
//  sinaweibo
//
//  Created by WGP on 16/4/19.
//  Copyright © 2016年 WGP. All rights reserved.
//

import UIKit
import SVProgressHUD

class HMComposeViewController: UIViewController {
    
    private var maxLengthOfText = 25
    
    private var isShowPickerView = false

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.whiteColor()
        setupUI()
        
//        监听键盘frame的变化
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("willChangeFrame:"), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
    }
    
    deinit
    {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
//    让texyView一出现就唤出键盘
    override func viewDidAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        
        if !isShowPickerView
        {
            textView.becomeFirstResponder()
        }
    }
    
    
//    MARK: - 键盘通知回掉方法
    @objc private func willChangeFrame(keyboardNotification: NSNotification)
    {
        let frame = keyboardNotification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        let duration = keyboardNotification.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        let offset = -(UIScreen.mainScreen().bounds.height-frame.origin.y)
        
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(offset)
        }
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    
    private func setupUI()
    {
//        1.添加控件
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: Selector("cancelItemDidClick"))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: Selector("sendItemDidClick:"))
        
        navigationController?.navigationBar.tintColor = UIColor.orangeColor()
        navigationItem.rightBarButtonItem!.enabled = false
        
        navigationItem.titleView = titleLabel
        
        view.addSubview(textView)
        setupPickerView()
        view.addSubview(toolBar)
        view.addSubview(tipLabel)
        
//        2.添加约束
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
        
        tipLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(toolBar.snp_top).offset(-4)
            make.right.equalTo(toolBar).offset(-4)
        }
    }
    
    private func setupPickerView()
    {
        let photoPickerView = pickerVC.view
        self.view.addSubview(photoPickerView)
        
        self.addChildViewController(pickerVC)
        
        photoPickerView.snp_makeConstraints { (make) -> Void in
            
            make.left.trailing.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(UIScreen.mainScreen().bounds.size.height * 0.6)
            make.height.equalTo(UIScreen.mainScreen().bounds.height * 0.6)
        }
    }
    
//    MARK: - 私有方法
    @objc private func cancelItemDidClick()
    {
        SVProgressHUD.dismiss()
        
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func sendItemDidClick(sendItem: UIBarButtonItem)
    {
//        发微博
        let text = textView.emoticonText()
        
//        判断长度是否超出
        let last = maxLengthOfText - text.characters.count
        if last < 0
        {
            SVProgressHUD.showErrorWithStatus("超出最大长度")
            return
        }
        
        SVProgressHUD.showWithStatus("正在发布微博...")
        
        let image = pickerVC.photos.first
        
        HMStatusViewModel.sharedInstance.sendStatus(text,image: image) { (error) -> () in
            if error != nil
            {
                SVProgressHUD.showErrorWithStatus("发送微博失败!")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
//                发布微博成功
                self.cancelItemDidClick()
            })
        }
    }
    
    @objc private func mention()
    {
        HMPrint("mention")
    }
    
    @objc private func emoticon(button: UIButton)
    {
//        切换表情键盘,不是赋值后立马切换,在键盘弹出之前,textView.inputView == nil就用系统的键盘
//        textView.inputView != nil就用设置的键盘
        
//        设置toolBar的那妞
        var normalImage: UIImage?
        var highlightedImage: UIImage?
        
//        退出键盘
        textView.resignFirstResponder()
        
//        之前是系统键盘就切换成我们的键盘,之前是我们的键盘就切换成系统的键盘
        textView.inputView = textView.inputView == nil ? emoticonKeyboard : nil
        
        if textView.inputView == nil
        {
//            系统键盘
            normalImage = UIImage(named: "compose_emoticonbutton_background")
            highlightedImage = UIImage(named: "compose_emoticonbutton_background_highlighted")
        }else
        {
//            自定义键盘
            normalImage = UIImage(named: "compose_keyboardbutton_background")
            highlightedImage = UIImage(named: "compose_keyboardbutton_background_highlighted")
        }
        
        button.setImage(normalImage, forState: .Normal)
        button.setImage(highlightedImage, forState: .Highlighted)
        
//        先等0.25秒,先让键盘动画下去,在烫出来
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.textView.becomeFirstResponder()
        }
        
    }
    
    @objc private func trend()
    {
        HMPrint("trend")
    }
    
    @objc private func picture()
    {
        isShowPickerView = true
        
        pickerVC.view.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(self.view).offset(0)
        }
        
        UIView.animateWithDuration(HMDefaultAnimationDuration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
        textView.resignFirstResponder()
    }
    
    @objc private func add()
    {
        HMPrint("add")
    }
    
//    MARK: - 懒加载
    private lazy var titleLabel: UILabel =
    {
        let label = UILabel()
        
        label.numberOfLines = 0
        label.textAlignment = .Center
        
        let prefix = "发微博"
        
        if let name = HMUserAccountViewModel.sharedInstance.userAccount!.screen_name
        {
            let title = prefix + "\n" + name
            
            let attrStrM = NSMutableAttributedString(string: title)
            
            let range = (title as NSString).rangeOfString(name)
            
            attrStrM.addAttribute(NSForegroundColorAttributeName, value: UIColor
                .lightGrayColor(), range: range)
            attrStrM.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
            
            label.attributedText = attrStrM
            
            label.sizeToFit()
            
        }else
        {
          label.text = prefix
        }
        return label
    }()
    
    private lazy var toolBar: UIToolbar =
    {
        let toolBar = UIToolbar()
        
        let itemSettings =
        [
            ["imageName":"compose_mentionbutton_background","action":"mention"],
            ["imageName":"compose_emoticonbutton_background","action":"emoticon:"],
            ["imageName":"compose_trendbutton_background","action":"trend"],
            ["imageName":"compose_toolbar_picture","action":"picture"],
            ["imageName":"compose_add_background","action":"add"],
        ]
        
        var items = [UIBarButtonItem]()
        var index = 0
        
        for dict in itemSettings
        {
            let imageName = dict["imageName"]
            let action = dict["action"]
            
            let item = UIBarButtonItem(imageName: imageName!, target: self, action: Selector(action!))
            items.append(item)
            
            let button = item.customView as! UIButton
            button.tag = index
            
//            添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
            
            index++
        }
        
        items.removeLast()
        
        toolBar.items = items
        
        return toolBar
    }()
    
    private lazy var textView: HMPlaceholderTextView =
    {
        let tv = HMPlaceholderTextView()
        
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.blackColor()
        
        tv.placeholderStr = "我是占位文本";
//        tv.text = "我是占位文本"
        tv.delegate = self
        
//        垂直弹簧效果
        tv.alwaysBounceVertical = true
        
//        拖拽就会关闭键盘
        tv.keyboardDismissMode = .OnDrag
        
        return tv
    }()
    
//    自定义表情键盘
    private lazy var emoticonKeyboard: HMEmoticonKeyboard =
    {
        let keyboard = HMEmoticonKeyboard()
        
        keyboard.textView = self.textView
        
        return keyboard
    }()
    
    ///长度提示
    private lazy var tipLabel: UILabel =
    {
        let label = UILabel(fontSize: 10, textColor: UIColor.lightGrayColor())
        
        label.text = String(self.maxLengthOfText)
        label.sizeToFit()
        
        return label
    }()
    
    private lazy var pickerVC: HMPhotoSelectorController = HMPhotoSelectorController()
}


extension HMComposeViewController: UITextViewDelegate
{
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        let text = textView.emoticonText()
        
        let last = maxLengthOfText - text.characters.count
        
        tipLabel.text = String(last)
        
        let color = last < 0 ? UIColor.redColor() : UIColor.lightGrayColor()
        
        tipLabel.textColor = color ;
    }
}





